export const responsiveArray = ["xxxl", "xxl", "xl", "lg", "md", "sm", "xs"]
export const responsiveMap = {
    xs: "(max-width:575px)",
    sm: "(min-width:576px)",
    md: "(min-width:768px)",
    lg: "(min-width:992px)",
    xl: "(min-width:1200px)",
    xxl: "(min-width:1600px)",
    xxxl: "(min-width:2000px)"
}
let subscribers = []
let subUid = -1
let screens = {}
export const ResponsiveObserver = {
    matchHandlers: {},
    dispatch(pointMap, breakpointChecked) {
        screens = pointMap
        if (!subscribers.length) {
            return false
        }
        subscribers.forEach(item => {
            item.func(screens, breakpointChecked)
        })
        return true
    },
    subscribe(func) {
        if (!subscribers.length) {
            this.register()
        }
        const token = (++subUid).toString()
        subscribers.push({ token, func })
        func(screens, null)
        return token
    },
    unsubscribe(token) {
        subscribers = subscribers.filter(item => item.token !== token)
        if (!subscribers.length) {
            this.unregister()
        }
    },
    unregister() {
        Object.keys(responsiveMap).forEach(screen => {
            const matchMediaQuery = responsiveMap[screen]
            const handler = this.matchHandlers[matchMediaQuery]
            if (handler && handler.mql && handler.listener) {
                handler.mql.removeEventListener("change", handler.listener)
            }
        })
    },
    register() {
        Object.keys(responsiveMap).forEach(screen => {
            const matchMediaQuery = responsiveMap[screen]
            const listener = ({ matches }) => {
                this.dispatch({
                    ...screens,
                    [screen]: matches
                }, screen)
            }
            const mql = window.matchMedia(matchMediaQuery)
            mql.addEventListener("change", listener)
            this.matchHandlers[matchMediaQuery] = {
                mql,
                listener
            }
            listener(mql)
        })
    }
}